package LeetCode刷题;

import java.util.Arrays;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-09-27 15:18
 * @description: Functions of this class is
 **/
public class No插入数组 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        if(intervals.length==0){
            return new int[][]{newInterval};
        }
        int ans[][]=new int[intervals.length+1][2];
        //先将原来集合中所有在新区间左边的区间放入到新数组中*
        int index=0;
        int i=0;
        while(i<intervals.length&&intervals[i][1]<newInterval[0]){
            ans[index++]=intervals[i++];
        }
        //然后开始将剩下区间中那些与新区间重复的进行合并,合并到新区见中*
        while(i<intervals.length&&newInterval[1]>=intervals[i][0]){
            newInterval[0]=Math.min(intervals[i][0],newInterval[0]);
            newInterval[1]=Math.max(intervals[i][1],newInterval[1]);
            i++;
        }
        ans[index++]=newInterval;//将新数组放入到答案集合中

        //然后把剩下的那些在新区间右边的区间放入到答案数组中*
        while(i<intervals.length){
            ans[index++]=intervals[i++];
        }
        return Arrays.copyOf(ans,index);
    }
}